const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const authenticator = require('../middleware/authenticator');

// 生成一个随机盐 
const salt = crypto.randomBytes(16).toString('hex');

const secretKey = 'pp7_secret_key';

const generateToken = (userId, username) => {
    const payload = {
        userId,
        username
    };
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
    return token;
};

// 定义一个函数，用于将角色名称转换为对应的英文缩写
function translateRole(role) {
    // 定义一个对象，用于存储角色名称和对应的英文缩写
    const roleMap = {
        "管理员": "admin",
        "编辑": "editor",
        "普通用户": "user"
    };
    return roleMap[role] || role; // 如果没有匹配的映射关系，返回原始角色名称
}


function userRouteModule(db) {

    // 注册接口
    router.post('/register', async (req, res) => {
        const { username, password, phone, email, gender } = req.body;
        // 创建哈希值
        const hash = crypto.createHmac('sha256', salt).update(password).digest('hex');
        const sql = 'INSERT INTO users (username, password, salt, phone, email, gender) VALUES (?,?,?,?,?,?)';

        try {
            const [rows] = await db.query('select * from users where username =?', [username]);
            if (rows.length > 0) {
                return res.status(401).send({ code: 401, message: '用户名已存在' });
            }

            const [result] = await db.query(sql, [username, hash, salt, phone, email, gender]);
            console.log(result, "result");
            res.status(200).send({ code: 200, msg: '注册成功' });

        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, msg: '服务器错误' });
        }
    });

    // 登录接口
    router.post('/login', async (req, res) => {
        const { username, password } = req.body;
        try {
            console.log(username, password, "username, password");
            const [rows] = await db.query(
                'SELECT id, salt, password FROM users WHERE username =?',
                [username]
            );

            if (rows.length === 0) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }

            const storedSalt = rows[0].salt;
            const storedHash = rows[0].password;
            const id = rows[0].id;

            // 使用相同的盐对输入的密码进行哈希处理
            const hash = crypto.createHmac('sha256', storedSalt).update(password).digest('hex');
            // 比较新生成的哈希值与数据库中存储的哈希值
            if (hash !== storedHash) {
                return res.status(401).send({ message: '用户名或密码错误' });
            }
            // 登录成功，生成 JWT
            const token = generateToken(id, username);

            // 返回 JWT
            res.header('Authorization', token).send({ code: 200, message: '登录成功', data: { token: token } });
        } catch (error) {
            console.log(error, "错误");
        }
    });

    // 得到用户信息
    // 得到用户信息和权限  authenticator, 
    router.get("/getInfo", async (req, res) => {
        const userId = req.query.userId; // 从查询参数中获取用户 ID
    
        if (!userId) {
            return res.status(400).send({ code: 400, message: '缺少用户ID' });
        }
    
        try {
            // 查询用户信息及角色
            const sql = `
                SELECT 
                    u.id as userId,
                    u.username,
                    u.phone,
                    u.email,
                    u.password,
                    u.gender,
                    GROUP_CONCAT(r.rolename SEPARATOR ',') as roles
                FROM 
                    users u
                LEFT JOIN user_role_relation ur ON u.id = ur.userid
                LEFT JOIN roles r ON ur.roleid = r.id
                WHERE 
                    u.id = ?
            `;
            const results = await db.query(sql, [userId]);
    
            if (results.length === 0) {
                return res.status(404).send({ code: 404, message: '用户未找到' });
            }
    
            const userInfo = results[0];
            console.log(userInfo)
            const roleInfo = userInfo.roles ? userInfo.roles.split(',').map(role => translateRole(role)) : [];
            
            console.log(roleInfo)

            res.send({
                code: 200,
                data: {
                    ...userInfo,
                    roles:roleInfo
                },
                message: "ok"
            });
        } catch (error) {
            console.error(error, "错误");
            res.status(500).send({ code: 500, message: '服务器错误' });
        }
    });

    return router;
}

module.exports = userRouteModule;